package com.cykj.v_m_sprintboot.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.io.InputStream;
/**
 * ftp文件服务器工具类
 */
public class FtpUtil {
    //ftp服务器ip地址
    private static final String FTP_ADDRESS = "121.43.147.36";
    //端口号
    private static final int FTP_PORT = 21;
    //用户名
    private static final String FTP_USERNAME = "user-cyx";
    //密码
    private static final String FTP_PASSWORD = "123456";
    //附件路径
    private static final String FTP_BASEPATH = "/home/user-file/files";


    public static boolean uploadFile(String fileName, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        ftp.enterLocalPassiveMode();		//这个设置允许被动连接--访问远程ftp时需要
        try {
            int reply;
            ftp.connect(FTP_ADDRESS, FTP_PORT);//连接服务器
            ftp.login(FTP_USERNAME,FTP_PASSWORD); //登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)){//判断ftp是否连接上
                ftp.disconnect();//如果没有连接上，断开
                return false;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//设置二进制的文件类型
            ftp.makeDirectory(FTP_BASEPATH);//创建文件夹
            ftp.changeWorkingDirectory(FTP_BASEPATH);//改变文件目录
            System.out.println("开始上传");
            ftp.storeFile(fileName,input);//传文件
            ftp.getBufferSize();
            System.out.println("上传成功");
            input.close();//输入流关闭
            ftp.logout();//ftp注销
            success =true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()){
                try {
                    ftp.disconnect();
                } catch (IOException ios) {
                    ios.printStackTrace();
                }
            }
        }
        return success;
    }
}
